import { HomeOutlined } from '@ant-design/icons';
import { Breadcrumb } from 'antd';
import { useMemo } from 'react';

// 面包屑项类型
interface BreadcrumbItem {
  title: React.ReactNode;
  href?: string;
  [key: `data-${string}`]: string | undefined;
}

interface SmartBreadcrumbProps {
  // 可选的自定义面包屑项，如果提供则使用自定义的
  customItems?: BreadcrumbItem[];
  // 是否显示首页
  showHome?: boolean;
  // 首页链接
  homeHref?: string;
  // 当前路径（可选，如果不提供则使用 window.location.pathname）
  currentPath?: string;
}

const SmartBreadcrumb: React.FC<SmartBreadcrumbProps> = ({
  customItems,
  showHome = true,
  homeHref = '/',
  currentPath,
}) => {
  // 生成面包屑项
  const breadcrumbItems = useMemo(() => {
    // 如果提供了自定义面包屑，直接使用
    if (customItems) {
      return customItems;
    }

    const items: BreadcrumbItem[] = [];

    // 添加首页
    if (showHome) {
      items.push({
        title: (
          <>
            <HomeOutlined />
            <span>首页</span>
          </>
        ),
        href: homeHref,
      });
    }

    // 获取当前路径
    const pathname = currentPath || (typeof window !== 'undefined' ? window.location.pathname : '/');

    // 根据路径生成面包屑项
    const pathSegments = pathname.split('/').filter(Boolean);

    pathSegments.forEach((segment, index) => {
      const isLast = index === pathSegments.length - 1;
      const href = '/' + pathSegments.slice(0, index + 1).join('/');

      items.push({
        title: segment,
        href: isLast ? undefined : href,
      });
    });

    return items;
  }, [customItems, showHome, homeHref, currentPath]);

  return (
    <div className="smart-breadcrumb">
      <Breadcrumb items={breadcrumbItems} />
    </div>
  );
};

export default SmartBreadcrumb;
